#encoding=utf-8
import geoip2.database
import io, sys
from geopy.geocoders import Nominatim
import re
import IPy
import requests
from bs4 import BeautifulSoup

"""使用IPy类库判断ip"""
def is_ip(address):
    try:
        IPy.IP(address)
        print("ip正确")
        pass
    except Exception as e:
        print("false")
        pass

"""正则判断ip"""
def check_ip(ipAddr):
    compile_ip=re.compile('^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$')
    if compile_ip.match(ipAddr):
        print('IP地址正确')
        pass
    else:
        print('false')
        pass

"""geopy定位"""
# geolocator = Nominatim()
# location = geolocator.geocode("河南省郑州市北三环")
# print(location)
# latitude = str(location.latitude)
# longitude = str(location.longitude)

# geocodeN("河南省郑州市南阳路兴隆铺路祥和花园")

"""api定位"""
def getAddress(ip):
    # is_ip("106.42.95.95")
    is_ip(ip)
    response = requests.get("https://ip.cn/index.php?ip={}".format(ip))
    soup = BeautifulSoup(response.content, 'lxml')
    a = soup.find('div', attrs={'class': 'well'})
    # address = a.find_all('code')[1].text
    print(a)
getAddress("106.42.95.95")

"""geoip2"""
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
# client = geoip2.database.Reader("/var/www/html/python/app/GeoLite2-City/GeoLite2-City.mmdb")
# ip = input("输入你要查询的IP:\n")
# check_ip(ip)
# response = client.city(ip)
# print(response)
#
# print("你查询的IP的地理位置是:")
#
# print("地区：{}({})".format(response.continent.names["es"],
#                                        response.continent.names["zh-CN"]))
#
# print("国家：{}({}) ，简称:{}".format(response.country.name,
#                                                         response.country.names["zh-CN"],
#                                                         response.country.iso_code))
#
# print("洲／省：{}({})".format(response.subdivisions.most_specific.name,
#                                           response.subdivisions.most_specific.names["zh-CN"]))
#
# print("城市：{}({})".format(response.city.name,
#                                           response.city.names["zh-CN"]))
#
# print("经度：{}，纬度{}".format(response.location.longitude,
#                                             response.location.latitude))
#
# print("时区：{}".format(response.location.time_zone))
#
# print("邮编:{}".format(response.postal.code))
